package com.southminority.ethnic.controller.admin.member;

import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.pojo.Member;
import com.southminority.ethnic.service.member.MemberService;
import com.southminority.ethnic.controller.member.vo.MemberVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 团队成员管理端接口
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "09 - 团队成员管理API", description = "【后台】团队成员的增删改查接口")
@RestController
@RequestMapping("/admin/team/member")
@CrossOrigin
public class MemberAdminController {

    private final MemberService memberService;

    public MemberAdminController(MemberService memberService) {
        this.memberService = memberService;
    }

    @GetMapping("/page")
    @Operation(summary = "分页和条件查询团队成员", description = "后台管理使用的团队成员列表接口，支持多种条件筛选和分页。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    public R<PageResult<MemberVO>> getMemberPageForAdmin(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页显示数量", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "姓名关键词", example = "张") @RequestParam(required = false) String name,
            @Parameter(description = "部门", example = "文学院") @RequestParam(required = false) String department,
            @Parameter(description = "职称", example = "教授") @RequestParam(required = false) String title,
            @Parameter(description = "状态", example = "1", schema = @Schema(description = "1-启用, 0-禁用", type = "integer", allowableValues = {"1", "0"})) @RequestParam(required = false) Integer status,
            @Parameter(description = "归属机构ID", example = "1") @RequestParam(required = false) Long organizationId) {
        try {
            PageResult<MemberVO> pageResult = memberService.getMemberPageForAdmin(page, size, name, department, title, status, organizationId);
            return R.ok(pageResult);
        } catch (Exception e) {
            log.error("管理员分页查询团队成员失败", e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }

    @GetMapping("/detail/{id}")
    @Operation(summary = "获取单个成员的详细信息（用于编辑）", description = "根据成员ID查询，返回其完整信息，包括被禁用的成员。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "团队成员不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<MemberVO> getMemberDetailForAdmin(@Parameter(description = "成员的唯一ID", example = "1", required = true) @PathVariable Long id) {
        try {
            MemberVO memberVO = memberService.getMemberDetailForAdmin(id);
            return R.ok(memberVO);
        } catch (Exception e) {
            log.error("管理员获取团队成员详情失败，ID: {}", id, e);
            return R.fail("获取详情失败: " + e.getMessage());
        }
    }

    @PostMapping("/create")
    @Operation(summary = "新增一个团队成员", description = "传入团队成员的完整信息（除ID外）来创建一个新的记录。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功，返回创建后的成员信息"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<MemberVO> createMember(@RequestBody(description = "团队成员信息的JSON对象", required = true,
            content = @Content(schema = @Schema(implementation = Member.class)))
            @org.springframework.web.bind.annotation.RequestBody Member member) {
        try {
            MemberVO memberVO = memberService.createMember(member);
            log.info("管理员创建团队成员成功，成员: {}", member.getName());
            return R.ok(memberVO);
        } catch (Exception e) {
            log.error("管理员创建团队成员失败", e);
            return R.fail("创建团队成员失败: " + e.getMessage());
        }
    }

    @PutMapping("/update/{id}")
    @Operation(summary = "根据ID更新成员信息", description = "提供成员的ID和更新后的信息，对现有记录进行修改。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功，返回更新后的成员信息"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "404", description = "团队成员不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<MemberVO> updateMember(
            @Parameter(description = "要更新的成员ID", example = "1", required = true) @PathVariable Long id,
            @RequestBody(description = "包含更新字段的成员JSON对象", required = true,
                    content = @Content(schema = @Schema(implementation = Member.class)))
                    @org.springframework.web.bind.annotation.RequestBody Member member) {
        try {
            MemberVO memberVO = memberService.updateMember(id, member);
            log.info("管理员更新团队成员成功，成员ID: {}", id);
            return R.ok(memberVO);
        } catch (Exception e) {
            log.error("管理员更新团队成员失败，成员ID: {}", id, e);
            return R.fail("更新团队成员失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "根据ID逻辑删除成员", description = "将指定ID的成员状态设置为-1（已删除），并非物理删除。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "团队成员不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> deleteMember(@Parameter(description = "要删除的成员ID", example = "1", required = true) @PathVariable Long id) {
        try {
            boolean result = memberService.deleteMember(id);
            log.info("管理员删除团队成员成功，成员ID: {}", id);
            return R.ok(result);
        } catch (Exception e) {
            log.error("管理员删除团队成员失败，成员ID: {}", id, e);
            return R.fail("删除团队成员失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量逻辑删除成员", description = "传入一个ID列表，批量将对应的成员状态设置为-1。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "批量删除成功"),
            @ApiResponse(responseCode = "400", description = "ID列表为空"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> batchDeleteMembers(
            @RequestBody(description = "包含多个成员ID的数组", required = true,
                    content = @Content(schema = @Schema(type = "array", implementation = Long.class))) List<Long> ids) {
        try {
            boolean result = memberService.batchDeleteMembers(ids);
            log.info("管理员批量删除团队成员成功，删除{}位成员", ids.size());
            return R.ok(result);
        } catch (Exception e) {
            log.error("管理员批量删除团队成员失败", e);
            return R.fail("批量删除团队成员失败: " + e.getMessage());
        }
    }

    @PutMapping("/status/{id}")
    @Operation(summary = "更新成员状态", description = "更新单个成员的状态，如启用（1）和禁用（0）。")
    @Parameters({
            @Parameter(name = "id", description = "成员ID", example = "1", required = true),
            @Parameter(name = "status", description = "新的状态值", example = "0", required = true,
                    schema = @Schema(description = "1-启用, 0-禁用", type = "integer", allowableValues = {"1", "0"}))
    })
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "状态更新成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "404", description = "团队成员不存在"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public R<Boolean> updateMemberStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        try {
            boolean result = memberService.updateMemberStatus(id, status);
            log.info("管理员更新成员状态成功，成员ID: {}，新状态: {}", id, status);
            return R.ok(result);
        } catch (Exception e) {
            log.error("管理员更新成员状态失败，成员ID: {}", id, e);
            return R.fail("更新成员状态失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/test")
    @Operation(summary = "测试接口连通性", description = "一个简单的GET请求，用于检查服务是否正常运行。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "服务正常")
    })
    public R<String> test() {
        return R.ok("团队成员管理服务正常");
    }
} 
